<template>
  <div class="common-warp wh100 warp-bg">
    <div class="noo">
      <a-card title="基本信息">
        <a-form ref="formaRef" :model="state.forma" :rules=rulesa>
          <a-form-item label="工号" name="code">
            <a-input v-model:value="state.forma.code" />
          </a-form-item>
          <a-form-item label="姓名" name="name">
            <a-input v-model:value="state.forma.name" />
          </a-form-item>
        </a-form>
      </a-card>

      <a-card title="工作信息" style="margin-top: 12px;">
        <a-form :model="state.formb">
          <a-form-item label="部门" name="name">
            <a-cascader v-model:value="state.formb.organizationCode" change-on-select
              :fieldNames="{ children: 'children', label: 'name', value: 'code' }" :options="state.organizationTree" />
          </a-form-item>
          <a-form-item label="职位" name="code">
            <a-cascader v-model:value="state.formb.positionCode" change-on-select
              :fieldNames="{ children: 'children', label: 'name', value: 'code' }" :options="state.positionTree" />
          </a-form-item>
          <a-form-item label="设备权限" name="protoType">
            <a-select ref="select" v-model:value="state.formb.privilege">
              <a-select-option :value="0">普通用户</a-select-option>
              <a-select-option :value="1">管理员</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>

      <a-card title="照片上传" style="margin-top: 12px;margin-bottom: 12px;">
        <div class="upload-warp" style="display: flex;justify-content: space-around">
          <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" name="avatar" list-type="picture-card"
            class="avatar-uploader" :show-upload-list="false" :before-upload="handleUploadAvatar">
            <img v-if="state.formc.avatarUrl" :src="state.formc.avatarUrl" alt="头像" width="100" height="100" />
            <div v-else>
              <div class="ant-upload-text">头像</div>
            </div>
          </a-upload>

          <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
            :before-upload="handleUploadBioPhoto">
            <img v-if="state.formc.bioPhotoUrl" :src="state.formc.bioPhotoUrl" alt="人脸" width="100" height="100" />
            <div v-else>
              <div class="ant-upload-text">人脸</div>
            </div>
          </a-upload>
        </div>

      </a-card>
    </div>
    <a-button type="primary" block @click="confirm(formaRef)">提交</a-button>
  </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted, } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import {
  usePersonEmployeeQueryApi,
  usePersonEmployeeUpdateApi,
  usePersonOrganizationListApi,
  usePersonPositionListApi,
  useSystemattAchmentCreateApi
} from '@/api/index'
import { message } from 'ant-design-vue';
import type { PositionItem } from '@/types/person/position';

const router = useRouter()
const route = useRoute()
const formaRef = ref();

const rulesa = {
  code: [{ required: true, message: '请输入工号', trigger: 'change' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
};
const useContenta = () => {
  return {
    code: "",
    name: "",
  }
}
const useContentb = () => {
  return {
    organizationCode: "",
    positionCode: "",
    privilege: 0,
  }
}
const useContentc = () => {
  return {
    avatarUrl: "",
    bioPhotoUrl: "",
  }
}

const state = reactive({
  forma: useContenta(),
  formb: useContentb(),
  formc: useContentc(),
  organizationTree: [] as any[],
  positionTree: [] as any[],
  organizationList: [],
  positionList: [],
})

const handleUploadBioPhoto = (fileInfo: File) => {
  if (!fileInfo.type.includes('image')) {
    message.error('图片格式不正确!')
    return false
  } else if (fileInfo.size / 1024 / 1024 > 10) {
    message.error('图片不能大于 10MB!')
    return false
  }
  const formData = new FormData();
  formData.append('file', fileInfo);
  useSystemattAchmentCreateApi(formData).then(({ data: { url } }) => {
    state.formc.bioPhotoUrl = url
    message.success('上传成功', 2)
  })
  return false
}

const handleUploadAvatar = async (fileInfo: File) => {
  if (!fileInfo.type.includes('image')) {
    message.error('图片格式不正确!')
    return false
  } else if (fileInfo.size / 1024 / 1024 > 10) {
    message.error('图片不能大于 10MB!')
    return false
  }
  const formData = new FormData();
  formData.append('file', fileInfo);
  useSystemattAchmentCreateApi(formData).then(({ data: { url } }) => {
    state.formc.avatarUrl = url
    message.success('上传成功', 2)
  })
  return false
}

const getOrganizationList = async () => {
  let { data } = await usePersonOrganizationListApi()
  data = data || []
  state.organizationTree = formatTree(data, '')
  state.organizationList = data
}
const getPositionList = async () => {
  let { data } = await usePersonPositionListApi()
  state.positionTree = formatTree(data, '')
  state.positionList = data
}

const formatTree = (data: PositionItem[], parentCode: string) => {
  let result = [] as any[];
  data.forEach((item: PositionItem) => {
    if (item.parentCode === parentCode) {
      let children = formatTree(data, item.code)
      if (children.length === 0) {
        children = null
      }
      item.children = children
      result.push(item)
    }
  });
  return result;
}

//根据路由参数搜索
const queryData = async (devcode: string) => {
  let { data: { code, name, privilege, organizationCode, positionCode, avatarUrl, bioPhotoUrl } } = await usePersonEmployeeQueryApi({ code: devcode })
  organizationCode = findParentCodeList(state.organizationList, organizationCode)
  positionCode = findParentCodeList(state.positionList, positionCode)

  state.forma = {
    code,
    name,
  }
  state.formb = {
    organizationCode,
    positionCode,
    privilege,
  }
  state.formc = {
    avatarUrl,
    bioPhotoUrl

  }
}

const findParentCodeList = (list, rowCode) => {
  console.log(list, rowCode, '111');

  let result = [rowCode]
  function find(data, code) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].code == code) {
        return data[i].parentCode
      }
    }
    return ''
  }
  let parentCode = find(list, rowCode) //第一次
  if (parentCode !== '') {
    result.push(parentCode)
  } else {
    return result
  }
  for (; ;) {
    parentCode = find(list, parentCode)
    if (parentCode !== '') {
      result.push(parentCode)
    }
    if (parentCode === '') {
      break
    }
  }
  result.reverse()
  return result
}


//提交
const confirm = (formRef: any) => {
  if (!formRef) return;
  formRef.validate().then(async () => {
    let torganizationCode = state.formb.organizationCode[state.formb.organizationCode.length - 1]
    let tpositionCode = state.formb.positionCode[state.formb.positionCode.length - 1]
    await usePersonEmployeeUpdateApi(Object.assign({}, { ...state.forma, ...state.formc }, { organizationCode: torganizationCode, positionCode: tpositionCode }))
    message.success("操作成功", 2);
    setTimeout(() => {
      router.push({ name: 'PersonEmployee' })
    }, 2300)
  })
};

onMounted(() => {
  document.title = '编辑'
  let { code }: any = route.query
  getOrganizationList()
  getPositionList()
  queryData(code)
})

</script>
<style scoped lang='less'>
.noo {
  height: calc(100vh - 56px);
  overflow-y: scroll;

  :deep(.ant-form-item-label) {
    padding: 0 !important;
  }

  :deep(.ant-card-body) {
    padding: 12px !important;
  }

  :deep(.ant-card-head) {
    padding: 12px !important;
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px !important;
  }

  .upload-warp {
    :deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper) {
      width: auto;
    }
  }
}
</style>